﻿using SuperX.Common;
using SuperX.Common.APIManager;
using SuperX.Common.Log;
using SuperX.Common.Respository;

namespace SuperX.WebSocketService
{
    public class WebSocketHost : HostService
    {
        private DynamicApiController controller;

        public override string ServiceType { get; set; }

        public WebSocketConfig Config { get; set; }

        public SocketManager SocketManager { get; set; }

        public override bool Exit()
        {
            return true;
        }

        public override bool Init()
        {
            SocketManager = new SocketManager(Config);
            controller = new WebSocketController(this);
            return true;
        }

        public override bool Load(string fileName)
        {
            FileName = fileName;
            Repository = new JsonRepository(FileName);
            Repository.Load(typeof(WebSocketConfig));
            Config = Repository.Model as WebSocketConfig;
            if (Config == null)
            {
                CreateCfgFile();
            }
            return true;
        }

        public override bool SaveAs(string fileName)
        {
            Repository = new JsonRepository(fileName) { Model = Config };
            Repository.Save();
            return true;
        }

        public override bool Start()
        {
            //server
            SocketManager.Start();

            Logger.Info($"{GetType().Name}启动");
            return true;
        }

        public override bool Stop()
        {
            Logger.Info($"{GetType().Name}停止...");
            SocketManager.Stop();
            return true;
        }

        private void CreateCfgFile()
        {
            WebSocketConfig config = new WebSocketConfig();
            config.SocketServer.IP = "0.0.0.0";
            config.SocketServer.Port = 9002;
            Config = config;
            SaveAs(FullFileName);
        }
    }
}